#!/usr/bin/env python
#coding=utf-8
from sqlalchemy import orm,Column,inspect,DateTime
from sqlalchemy.orm.attributes import manager_of_class
from Applications.extensions import db
from datetime import datetime

class baseModel(db.Model):
    __abstract__ = True

    def __init__(self):
        name: str = self.__class__.__name__
        if not hasattr(self, '__tablename__'):
            self.__tablename__ = camel2line(name)

    #def _set_fields(self):
    #    self._exclude = []

    #def set_attrs(self, attrs_dict):
    ##    for key, value in attrs_dict.items():
    #        if hasattr(self, key) and key != 'id':
     #           setattr(self, key, value)

    def to_json(self):
        dict = self.__dict__
        if "_sa_instance_state" in dict:
            del dict["_sa_instance_state"]
        return dict

    @classmethod
    def get_spage(cls, page=1,pagecurrent=10, where=None, order=None):

        _where = where
        _dummy_table = manager_of_class(cls).mapper.mapped_table
        _primary_key = _dummy_table.primary_key.columns
        _columns = _dummy_table.columns

        _primary_key = ",".join(["{0}".format(x) for x in _primary_key ])
        _fields = ",".join(["{0}".format(x) for x in _columns ])

        if where is None:
            _where = ''

        _params = 'CALL `sp_page`("{0}", "{1}", {2}, "{3}", {4}, {5}, @_totalcount, @_pagecount)'.format(
            _fields,
            cls.__tablename__,
            "'%s'"%(_where),
            _primary_key,
            page,
            pagecurrent
        )

        _list = db.session.execute(_params).fetchall()
        _return_count= db.session.execute('SELECT @_pagecount, @_totalcount').fetchone()
        _pagecount = _return_count[0]
        _totalcount = _return_count[1]
        return _list,_pagecount,_totalcount






''':cvar

类型名	Python类型	说明
Integer 	int 	普通整数，一般是 32 位
SmallInteger 	int 	取值范围小的整数，一般是 16 位
Big Integer 	int 或 long 	不限制精度的整数
Float 	float 	浮点数
Numeric 	decimal.Decimal 	定点数
String 	str 	变长字符串
Text 	str 	变长字符串，对较长或不限长度的字符串做了优化
Unicode 	unicode 	变长 Unicode 字符串
Unicode Text 	unicode 	变长 Unicode 字符串，对较长或不限长度的字符串做了优化
Boolean 	bool 	布尔值
Date 	datetime.date 	日期
Time 	datetime.time 	时间
DateTime 	datetime.datetime 	日期和时间
Interval 	datetime.timedelta 	时间间隔
Enum 	str 	一组字符串
PickleType 	任何 Python 对象 	自动使用 Pickle 序列化
LargeBinary 	str 	二进制文件

'''